<template>
  <div class="dropdown-buttons">
    <el-dropdown
      split-button
      type="primary"
      @click="handleClick"
      @command="handleCommand"
    >
      <i :class="mainButton.icon" class="dropdown-buttons__main-button"></i>
      {{ mainButton.title }}
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item
          v-for="button in dropdownButtons"
          :key="button.command"
          :icon="button.icon"
          :command="button.command"
        >
          {{ button.title }}</el-dropdown-item
        >
      </el-dropdown-menu>
    </el-dropdown>

    <el-upload
      v-for="button in uploadButtons"
      :id="button.upload._UUID_"
      :key="button.upload._UUID_"
      class="dropdown-buttons__upload"
      action=""
      :show-file-list="false"
      v-bind="button.upload"
    >
      {{ button.title }}
    </el-upload>
  </div>
</template>

<script>
/**
 * 下拉按钮组
 * 支持按钮点击回调 @command
 * 支持导入功能，按钮配置增加upload:{accept:String,httpRequest:Function}
 */
export default {
  name: 'DropdownButtons',
  props: {
    buttons: {
      type: Array,
      default: () => []
    }
  },

  computed: {
    mainButton () {
      return this.buttons[0]
    },
    dropdownButtons () {
      return this.buttons.filter((btn, index) => index)
    },
    uploadButtons () {
      return this.buttons.filter((btn) => {
        if (btn.upload) {
          btn.upload._UUID_ = `${btn.command}_${String(Math.random()).substring(2)}`
        }
        return btn.upload
      })
    }
  },

  methods: {
    handleClick () {
      this.handleCommand(this.mainButton.command)
    },

    handleCommand (command) {
      this.$emit('command', command)
      const button = this.uploadButtons.find(btn => btn.command === command)
      if (button?.upload) {
        document.querySelector(`#${button?.upload?._UUID_} .el-upload__input`).click()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dropdown-buttons{
  display: inline-block;

  &__main-button{
    margin-right: 5px;
  }

  &__upload{
    display: none;
  }
}
</style>
